// 引入
import {
  Card,
  Button,
  Table,
  Modal,
  Form,
  Input,
  Upload,
  message,
  Popconfirm,
  Select,
  Tag,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from '@ant-design/icons';
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
} from '@/api/product/category';
import {
  delAttrApi,
  getAttrListApi,
  saveAttrListApi,
} from '@/api/product/attr';
import { useEffect, useRef, useState } from 'react';
import {
  Category1ListModel,
  Category2ListModel,
  Category3ListModel,
} from '@/api/product/model/categoryModel';
import './index.less';
import type { ColumnsType } from 'antd/es/table';
import {
  AttrListModel,
  AttrValueListModel,
} from '@/api/product/model/attrModel';
import { randomInt } from 'crypto';
import { log } from 'console';
import type { InputRef } from 'antd';

function Attr() {
  // 声明状态-----------------------------------------------------------------
  const [category1Id, setCategory1Id] = useState(0);
  const [category2Id, setCategory2Id] = useState(0);
  const [category3Id, setCategory3Id] = useState(0);
  const [category1List, setCategory1List] = useState([]);
  const [category2List, setCategory2List] = useState([]);
  const [category3List, setCategory3List] = useState([]);
  // 显示添加编辑或者查询的标识
  const [isQuery, setIsQuery] = useState(true);

  // 平台属性列表
  const [attrList, setAttrList] = useState<AttrListModel>([]);

  // 平台属性值列表
  const [attrValueList, setAttrValueList] = useState<any>([]);

  // 编辑模式的标识
  // const [isEdit, setIsEdit] = useState(true);

  // 存储属性名称
  const [attrName, setAttrName] = useState('');

  // 收集属性
  // const [attrInfo, setAttrInfo] = useState([
  //   {
  //     attrName: '',
  //     attrValueList: [{ valueName: '' }],
  //     categoryId: 1,
  //     categoryLevel: 3,
  //   },
  // ]);
  // const [attrValueInfoList,setAttrValueInfoList]=useState(
  //     [
  //         {valueName:'1111',isEdit:false},
  //         {valueName:'2222',isEdit:true}
  //     ]
  // )

  // 判断是添加还是修改的标识
  const [isAdd, setIsAdd] = useState(false);
  // 声明状态-----------------------------------------------------------------

  const inputRef = useRef<InputRef>(null);
  const sharedProps = {
    ref: inputRef,
  };

  useEffect(() => {
    // 挂载的时候请求数据
    getcategory1List();
  }, []);

  // 请求一级分类的函数
  const getcategory1List = async () => {
    // 发送请求
    const result = await getCategory1ListApi();
    // 将拿到的值进行处理，Select和Option组件所需要的键名是label和value，需要对result的数据进行处理（替换键名）
    const res = result.map((item) => {
      return {
        label: item['name'],
        value: item['id'],
      };
    });
    // 给状态重新赋值
    setCategory1List(res as any);
    setCategory3List([]);
  };

  // 请求二级分类的函数
  const getcategory2List = async (id1: number) => {
    const result = await getCategory2ListApi(id1);
    const res = result.map((item) => {
      return {
        label: item['name'],
        value: item['id'],
      };
    });
    setCategory2List(res as any);
  };

  // 请求三级分类的函数
  const getcategory3List = async (id2: number) => {
    const result = await getCategory3ListApi(id2);
    const res = result.map((item) => {
      return {
        label: item['name'],
        value: item['id'],
      };
    });
    setCategory3List(res as any);
  };

  // 请求平台属性的函数
  const getAttrList = async (value: number) => {
    // 发送请求，因为category3Id还未更新，直接使用传递过来的形参进行请求
    const result = await getAttrListApi(category1Id, category2Id, value);
    // 给属性列表重新赋值
    setAttrList(result as any);
  };

  // 选中一级分类触发的函数
  const changeCategory1 = (value: number) => {
    // 拿到最新的category1Id
    setCategory1Id(value);
    // 清空category2List和category3List的值
    setCategory2List([]);
    setCategory3List([]);
    setCategory2Id(0);
    setCategory3Id(0);

    // 拿到最新的category1Id后发起category2List的数据请求
    getcategory2List(value);
  };
  // 选中二级分类触发的函数
  const changeCategory2 = (value: number) => {
    setCategory2Id(value);
    setCategory3List([]);
    getcategory3List(value);
    setCategory3Id(0);
  };
  // 选中三级分类触发的函数
  const changeCategory3 = (value: number) => {
    // 拿到最新的category3Id
    setCategory3Id(value);
    // 调用获取平台属性列表的请求函数
    getAttrList(value);
  };

  // 进入修改或者添加
  const alterIsQuery = (row: any) => {
    console.log(row);
    if (row.id) {
      setAttrName(row.attrName);
      setAttrValueList(row.attrValueList);
    }
    console.log(row);

    console.log('修改');
    setIsQuery(false);
  };

  // 属性名的change事件
  const attrNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setAttrName(e.target.value);
  };

  // 返回平台属性列表页面
  const goBack = () => {
    setIsQuery(true);
    getAttrList(category3Id);
    setAttrName('');
    setAttrValueList([]);
  };

  // const randomid = randomInt(1,5)
  // const valueList=[
  //     {
  //        id:1,valueName:'1111',isEdit:false
  //     },
  //     {
  //        id:2,valueName:'2222',isEdit:false
  //     }
  // ]
  // console.log(valueList);
  // console.log('toLook');
  // 切换到查看模式
  const toLook = (row: any, index: any) => {
    if (row.valueName == '') {
      attrValueList.splice(index, 1);
    } else {
      attrValueList.forEach((item: any) => {
        if (attrValueList.length == 0) return;
        if (item.id == row.id) {
          item.isEdit = !row.isEdit;
        }
      });
    }

    console.log(attrValueList);
    setAttrValueList((attrValueList: any) => {
      return [...attrValueList];
    });
    // console.log(attrValueList);
  };

  // 切换到编辑模式
  const toEdit = (row: any) => {
    // console.log(row.id, 'toEdit');
    console.log(attrValueList);
    if (attrValueList.length == 0) {
    } else {
      attrValueList.forEach((item: any) => {
        if (item.id == row.id) {
          item.isEdit = !row.isEdit;
          // console.log(item.valueName,row.isEdit,item.isEdit);
        }
      });
    }

    setAttrValueList((attrValueList: any) => {
      return [...attrValueList];
    });
    setTimeout(() => {
      inputRef.current!.focus({
        cursor: 'end',
      });
    }, 100);
  };

  // 点击添加属性值的函数
  const addAttrValue = () => {
    // if (attrValueList.length == 0) {
    let sj = ~~(Math.random() * (10000 - 999) + 1);

    const attrValue = {
      id: sj,
      valueName: '',
      isEdit: true,
    };

    setAttrValueList((attrValueList: any) => {
      return [...attrValueList, attrValue];
    });
  };

  // 输入框的change事件函数
  const attrValueInputChange = (
    e: React.ChangeEvent<HTMLInputElement>,
    row: any
  ) => {
    console.log('改变了', e.target.value);
    console.log(e);
    attrValueList.forEach((item: any) => {
      if (item.id == row.id) {
        item.valueName = e.target.value;
      }
    });
    setAttrValueList((attrValueList: any) => {
      return [...attrValueList];
    });

    // console.log(row.id, 'row');
  };

  // 删除平台属性值
  const delValue = (row: any, index: any) => {
    console.log(index);
    attrValueList.splice(index, 1);
    setAttrValueList((attrValueList: any) => {
      return [...attrValueList];
    });
  };

  // 保存添加和修改的按钮点击事件函数
  const saveAttr = async () => {
    attrValueList.forEach((item: any) => {
      delete item.id;
      delete item.isEdit;
    });
    setAttrValueList((attrValueList: any) => {
      return [...attrValueList];
    });
    await saveAttrListApi({
      attrName: attrName,
      attrValueList: attrValueList,
      categoryId: category3Id,
      categoryLevel: 3,
    });
    message.success('保存成功!');
    getAttrList(category3Id);
    setIsQuery(true);
  };

  // 删除平台属性的函数
  const delAttr = async (id: number) => {
    await delAttrApi(id);
    message.success('删除成功!');
    getAttrList(category3Id);
  };

  // AttrList表格的数据
  const columns: ColumnsType<any> = [
    {
      title: '序号',
      align: 'center',
      width: 80,
      render(value, row, index) {
        return index + 1;
      },
    },
    {
      title: '属性名称',
      dataIndex: 'attrName',
      key: 'attrName',
      width: 200,
      align: 'center',
    },
    {
      title: '属性值列表',
      render: (row: any) => (
        <>
          {row.attrValueList.map((item: any) => {
            return (
              <Tag color="green" key={item.id}>
                {item.valueName}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: '操作',
      render: (row: any) => (
        // 编辑和删除结构
        <>
          <Button
            type="primary"
            icon={<EditOutlined />}
            onClick={() => {
              alterIsQuery(row);
            }}
          ></Button>

          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => {
              delAttr(row.id);
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              style={{ marginLeft: 10 }}
              icon={<DeleteOutlined />}
              danger
            ></Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  // AttrValueList表格的数据
  const column_value: ColumnsType<any> = [
    {
      title: '序号',
      align: 'center',
      width: 80,
      render(value, row, index) {
        return index + 1;
      },
    },
    {
      title: '属性值名称',
      width: 400,
      render: (row: any, x, index) => (
        <>
          {row.isEdit ? (
            <Input
              onChange={(e) => {
                attrValueInputChange(e, row);
              }}
              value={row.valueName}
              onBlur={() => {
                toLook(row, index);
              }}
            />
          ) : (
            <span
              className="span_attrValue"
              onClick={() => {
                toEdit(row);
              }}
            >
              {row.valueName}
            </span>
          )}
        </>
      ),
    },
    {
      title: '操作',
      render: (row: any, x, index) => (
        <>
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={() => {
              delValue(row, index);
            }}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" icon={<DeleteOutlined />} danger></Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <div>
      {/* 分类结构 */}
      <Card style={{ width: 1720 }}>
        <div className="category">
          <label>一级分类</label>
          <Select
            showArrow
            style={{ width: 170 }}
            placeholder="请选择一级分类"
            // optionFilterProp="children"
            className="category_select"
            onChange={changeCategory1}
            options={category1List}
            disabled={!isQuery}
          />
        </div>
        <div className="category">
          <label>二级分类</label>
          <Select
            showArrow
            placeholder="请选择二级分类"
            notFoundContent="请选择一级分类"
            // optionFilterProp="children"
            className="category_select"
            style={{ width: 170 }}
            onChange={changeCategory2}
            options={category2List}
            disabled={!isQuery}
          />
        </div>
        <div className="category">
          <label>三级分类</label>
          <Select
            showArrow
            placeholder="请选择三级分类"
            notFoundContent="请选择二级分类"
            // optionFilterProp="children"
            className="category_select"
            onChange={changeCategory3}
            style={{ width: 170 }}
            options={category3List}
            disabled={!isQuery}
          />
        </div>
      </Card>
      {/* 根据三元表达式判断是添加修改还是查询模式，显示不同的Card */}
      {isQuery ? (
        <Card className="card_content">
          {/* 添加平台属性按钮 */}
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => {
              alterIsQuery({});
            }}
            disabled={category3Id == 0 ? true : false}
          >
            添加属性
          </Button>
          {/* 平台属性表格结构 */}
          <Table
            className="attrList_tab"
            rowKey="id"
            columns={columns}
            dataSource={attrList}
            bordered
            pagination={false}
          />
        </Card>
      ) : (
        <Card className="card_content">
          <p>
            <label style={{ fontSize: 16 }}>属性名</label>
            <Input
              placeholder="请输入属性名"
              style={{ width: 200, marginLeft: 15 }}
              value={attrName}
              onChange={attrNameChange}
            />
          </p>
          <p>
            <Button
              type="primary"
              className="btn_Save"
              icon={<PlusOutlined />}
              onClick={addAttrValue}
            >
              添加属性值
            </Button>
            <Button
              onClick={() => {
                goBack();
              }}
            >
              返回
            </Button>
          </p>
          <Table dataSource={attrValueList} columns={column_value} />
          <br />
          <p>
            <Button type="primary" className="btn_Save" onClick={saveAttr}>
              保存
            </Button>
            <Button
              onClick={() => {
                goBack();
              }}
            >
              返回
            </Button>
          </p>
        </Card>
      )}
    </div>
  );
}

export default Attr;
